package com.dousb.oj.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dousb.oj.common.ErrorCode;
import com.dousb.oj.constant.CommonConstant;
import com.dousb.oj.exception.BusinessException;
import com.dousb.oj.judge.JudgeService;
import com.dousb.oj.mapper.QuestionSubmitMapper;
import com.dousb.oj.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.dousb.oj.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.dousb.oj.model.entity.Question;
import com.dousb.oj.model.entity.QuestionSubmit;
import com.dousb.oj.model.entity.User;
import com.dousb.oj.model.enums.QuestionSubmitLanguageEnum;
import com.dousb.oj.model.enums.QuestionSubmitStatusEnum;
import com.dousb.oj.model.vo.QuestionSubmitVO;
import com.dousb.oj.service.QuestionService;
import com.dousb.oj.service.QuestionSubmitService;
import com.dousb.oj.service.UserService;
import com.dousb.oj.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author 豆沙包
 * @description 针对表【question_submit(题目提交)】的数据库操作Service实现
 * @createDate 2025-06-09 08:28:07
 */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
        implements QuestionSubmitService {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;

    @Resource
    @Lazy
    private JudgeService judgeService;

    /**
     * 提交题目
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        // 获取编程语言类型
        String language = questionSubmitAddRequest.getLanguage();
        // 根据编程语言类型获取枚举
        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        // 如果编程语言类型不存在，抛出异常
        if (languageEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "编程语言类型错误");
        }
        // 获取题目ID
        Long questionId = questionSubmitAddRequest.getQuestionId();
        // 判断实体是否存在，根据类别获取实体
        Question question = questionService.getById(questionId);
        // 如果实体不存在，抛出异常
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 是否已提交题目
        long userId = loginUser.getId();
        // 每个用户串行提交题目
        QuestionSubmit questionSubmit = new QuestionSubmit();
        // 设置用户ID
        questionSubmit.setUserId(userId);
        // 设置题目ID
        questionSubmit.setQuestionId(questionId);
        // 设置代码
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        // 设置编程语言类型
        questionSubmit.setLanguage(questionSubmitAddRequest.getLanguage());
        // 设置状态为等待
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        // 设置判题信息为空
        questionSubmit.setJudgeInfo("{}");
        // 保存题目提交信息
        boolean save = this.save(questionSubmit);
        // 如果保存失败，抛出异常
        if (!save) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据插入失败");
        }
        Long questionSubmitId = questionSubmit.getId();
        //执行判题服务 异步
        CompletableFuture.runAsync(() -> {
                    judgeService.doJudge(questionSubmitId);
                }
        );
        // 返回题目提交ID
        return questionSubmitId;
    }

    /**
     * 获取查询包装类 用户
     * 用户根据哪些字段查询 根据前端处理的对象
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();

        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();
        // 拼接查询条件
        queryWrapper.eq(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "status", status);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取题目
     *
     * @param questionSubmit
     * @param loginUser
     * @return
     */
    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        //将QuestionSubmit对象转换为QuestionSubmitVO对象
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        //仅本人和管理员能看见自己（提交userld和登录用户id不同）提交的代码
        //获取登录用户的id
        Long userId = loginUser.getId();
        //如果登录用户的id和提交用户的id不同，且登录用户不是管理员，则将代码置为null
        if (userId != questionSubmit.getUserId() && !userService.isAdmin(loginUser)) {
            questionSubmitVO.setCode(null);
        }
        //返回QuestionSubmitVO对象
        return questionSubmitVO;
    }

    /**
     * 题目分页
     *
     * @param questionSubmitPage
     * @param loginUser
     * @return
     */
    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        // 获取问题列表
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        // 创建问题视图对象分页
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        // 如果问题列表为空，则直接返回问题视图对象分页
        if (CollUtil.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        // 将问题列表转换为问题视图对象列表
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream().map(questionSubmit -> {
            return getQuestionSubmitVO(questionSubmit, loginUser);
        }).collect(Collectors.toList());
        // 设置问题视图对象分页的记录
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        // 返回问题视图对象分页
        return questionSubmitVOPage;
    }
}




